#!/usr/bin/env python

import re

from post import Post
from datetime import datetime
from HTMLParser import HTMLParser
from os import path

class LiveSpaceProvider():
    try:
        from BeautifulSoup import BeautifulSoup
    except ImportError as err:
        raise ImportError(err, "you must install BeautifulSoup(http://www.crummy.com/software/BeautifulSoup/) to work against LiveSpace") 
    
    def __init__(self, file_path):
        if not path.isdir(file_path + path.sep):
            raise IOError(file_path + ' is not a directory')
        self.file_path = file_path + path.sep

    def GetPosts(self, max_posts_num = 19, start_date = datetime.min.replace(year=1900), end_date = datetime.max):
# http://www.crummy.com/software/BeautifulSoup/documentation.html
        soup = LiveSpaceProvider.BeautifulSoup(open(self.file_path+"index.html"))
        list = soup('a')
        html = HTMLParser()
        posts = []

        for item in list:
            if len(posts) == max_posts_num:
                break
            href = item['href']
            item_soup = LiveSpaceProvider.BeautifulSoup(open(self.file_path+href))
            item_id = 'bp-' + href.partition('.html')[0] + '-Title'
            entry_title = unicode(item_soup(id=item_id)[0].contents[0])

            item_id = 'bp-' + href.partition('.html')[0] + '-publish'
            entry_publish = item_soup.findAll(id=item_id)[0].contents[0]
            entry_create = datetime.strptime(html.unescape(entry_publish[:-3]), '%m/%d/%Y %H:%M:%S') 
            if entry_create < start_date or entry_create > end_date:
                continue

            item_id = 'bp-' + href.partition('.html')[0] + '-content'
            entry_content = ''
            for line in item_soup.find(id=item_id).contents:
                entry_content = entry_content + unicode(line)

            item_id = 'bp-' + href.partition('.html')[0] + '-comments'
            post = Post(title=entry_title, content=entry_content, create_date=entry_create)
            posts.append(post)
         
        return posts

    def AddPost(self, post):
        raise NotImplementedError("AddPost is not implemented")

    def UpdatePost(self, post):
        raise NotImplementedError("UpdatePost is not implemented")

    def DeleteAllPosts(self):
        raise NotImplementedError("DeleteAllPosts is not implemented")
